package L614;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: javase
 * @description: 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 * @author: luolidong
 * @create: 2021-06-14 09:37
 * @version: 1.0
 */
public class Demo {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list=new ArrayList<>();
        if(matrix.length==0) return list;
        int top=0,bottom=matrix.length-1;
        int left=0,right=matrix[0].length-1;
        int numCount=matrix.length*matrix[0].length;

        while (numCount>0){
//            从左向右
            for (int i = left; i <= right &&numCount>0 ; i++) {
                list.add(matrix[top][i]);
                numCount--;
            }
            top++;
            for (int i = top; i <=bottom&&numCount>0  ; i++) {
                list.add(matrix[i][right]);
                numCount--;

            }
            right--;
            for (int i = right; i >=left&&numCount>0 ; i--) {
                list.add(matrix[bottom][i]);
                numCount--;

            }
            bottom--;
            for (int i = bottom; i >=top&&numCount>0 ; i--) {
                list.add(matrix[i][left]);
                numCount--;

            }
            left++;
        }
        return list;
    }

    public static void main(String[] args) {
        int[][] m={{1,2,3},{4,5,6},{7,8,9}};
        List<Integer> list = new Demo().spiralOrder(m);
        System.out.println(list);
    }
}
